package com.rds.material.liftcycle;
import com.rds.common.ServiceException;
import com.rds.common.api.material.domain.MaterialBill;
import com.rds.common.api.material.domain.RdaPartsRel;
import com.rds.common.core.domain.AjaxResult;
import com.rds.material.service.IMaterialBillService;
import com.rds.material.service.IRdaPartsRelService;
//import com.rds.system.common.LifecycleUtil;
//import com.rds.system.common.history.HistoryRecordUtil;
import com.rds.material.utils.WorkspaceUtils;
import com.rds.system.service.*;


import java.util.List;
import java.util.Map;

/**
 * 此类主要用作生命周期相关操作(单独给物料用)
 * @version : 1.0
 * @Copyright: Copyright(c) 2020-2021 All right reserved
 * @Company: GUANGZHOU RDS Co.,LTD
 * @author: Lijiasen
 * @create Date : 2022/12/11 : 22:50
 */

/**
 *zheng'qu
 */
public class partLifeCycleUtil {
    private final IRdaStateService rdaStateService;

    /**历史记录持久化 2021-12-13**/
    private ISysHistoryService sysHistoryService;

    private IRdaPartsRelService rdaPartsRelService;

    private IMaterialBillService materialBillService;

    private IRdaTypeService rdaTypeService;

    private IRdaPolicyService rdaPolicyService;


    public partLifeCycleUtil(IRdaStateService  rdaStateService){
        this.rdaStateService = rdaStateService;
    }

    /*************************************** 历史记录写进数据库-持久化 2021-12-13 [begin] **********************************************************/
    public partLifeCycleUtil(IRdaStateService rdaStateService,ISysHistoryService sysHistoryService, IRdaPartsRelService rdaPartsRelService, IMaterialBillService materialBillService,IRdaTypeService rdaTypeService,IRdaPolicyService rdaPolicyService){
        this.rdaStateService = rdaStateService;
        this.sysHistoryService = sysHistoryService;
        this.rdaPartsRelService = rdaPartsRelService;
        this.materialBillService = materialBillService;
        this.rdaTypeService = rdaTypeService;
        this.rdaPolicyService = rdaPolicyService;
    }



    /*************************************** 历史记录写进数据库-持久化 2021-12-13 [end] **********************************************************/
    /**
     * 当前方法只针对流程对象提升/降低生命周期操作
     * @param id 当前对象Id
     * @param policyid 策略Id
     * @param event 提升/降级
     * @param moduleName 模块名称
     * @param appointTargetStateId 指定到的状态Id
     * @return 提升信息
     */
    public AjaxResult goToTargetState(Long id, Long policyid, String event, String moduleName,Long appointTargetStateId){
        //进行判断，如果下级存在物料不是发布状态，则不允许发布
        Map<String,Object> dmap= WorkspaceUtils.getTypePolicyStates("EC Part","1",rdaTypeService,rdaPolicyService,rdaStateService);
        Map<String,Object> dstateMap=(Map)dmap.get("Stateid");
        //查询当前状态，如何是批准状态则进行卡控
        RdaPartsRel rdaPartsRelF = rdaPartsRelService.selectBillByRelId(id);

        if ("promote".equals(event) && dstateMap.get("Approved").toString().equals(rdaPartsRelF.getMaterialBill().getStateid().toString())){
            RdaPartsRel rdaPartsRel1 = new RdaPartsRel();
            rdaPartsRel1.setId(id);
            List<RdaPartsRel> relAndBill = rdaPartsRelService.billofMaterial(rdaPartsRel1);
            for (RdaPartsRel rdaPartsRel : relAndBill) {
                if (!rdaPartsRel.getId().equals(id) && !dstateMap.get("Release").toString().equals(rdaPartsRel.getMaterialBill().getStateid().toString())){
                    throw new ServiceException("下级物料："+rdaPartsRel.getMaterialBill().getName()+"不是发布状态");
                }
            }

        }


        if("part".equalsIgnoreCase(moduleName)){
            RdaPartsRel rdaPartsRel = rdaPartsRelService.selectRdaPartsRelById(id);
            MaterialBill materialBill = materialBillService.selectMaterialBillById(rdaPartsRel.getFromid());
            int currentStateId = materialBill.getStateid();
            System.out.println("PartLifeCycleUtil[74]:"+event+"--->>>currentStateId:" + currentStateId);
            /*获取当前策略下的所有状态**/
            Map<String, Object> eventMap = getToBeSetStateMap(Long.parseLong(materialBill.getPolicyid().toString()),currentStateId,event,appointTargetStateId);
            if ("0".equals(String.valueOf(eventMap.get("code")))) {
                int targetStateId = parseString2Int(String.valueOf(eventMap.get("targetStateId")));
                materialBill.setStateid(targetStateId);
                int rows = materialBillService.updateMaterialBill(materialBill);
//                new HistoryRecordUtil(rdaStateService,sysHistoryService).lifeCycleHistory(id,currentStateId,targetStateId,event);
                return  rows > 0 ? AjaxResult.success((String) eventMap.get("msg")) : AjaxResult.error("提升失败!");
            } else if ("-1".equals(String.valueOf(eventMap.get("code")))) {
                return AjaxResult.error((String) eventMap.get("msg"));
            }else{
                return AjaxResult.error( "出现未知错误,请联系管理员!");
            }
        } else {
            return AjaxResult.success(event+"对象类型不存在,请联系管理员!");
        }
    }

    /**
     * 对下级不进行卡控
     * @param id
     * @param policyid
     * @param event
     * @param moduleName
     * @param appointTargetStateId
     * @return
     */
    public AjaxResult goToTargetStates(Long id, Long policyid, String event, String moduleName,Long appointTargetStateId){
        if("part".equalsIgnoreCase(moduleName)){
            MaterialBill materialBill = materialBillService.selectMaterialBillById(id);
            int currentStateId = materialBill.getStateid();
            System.out.println("PartLifeCycleUtil[74]:"+event+"--->>>currentStateId:" + currentStateId);
            /*获取当前策略下的所有状态**/
            Map<String, Object> eventMap = getToBeSetStateMap(Long.parseLong(materialBill.getPolicyid().toString()),currentStateId,event,appointTargetStateId);
            if ("0".equals(String.valueOf(eventMap.get("code")))) {
                int targetStateId = parseString2Int(String.valueOf(eventMap.get("targetStateId")));
                materialBill.setStateid(targetStateId);
                int rows = materialBillService.updateMaterialBill(materialBill);
//                new HistoryRecordUtil(rdaStateService,sysHistoryService).lifeCycleHistory(id,currentStateId,targetStateId,event);
                return  rows > 0 ? AjaxResult.success((String) eventMap.get("msg")) : AjaxResult.error("提升失败!");
            } else if ("-1".equals(String.valueOf(eventMap.get("code")))) {
                return AjaxResult.error((String) eventMap.get("msg"));
            }else{
                return AjaxResult.error( "出现未知错误,请联系管理员!");
            }
        } else {
            return AjaxResult.success(event+"对象类型不存在,请联系管理员!");
        }
    }

    /**
     * 处理当前对象是否是提升/降级
     * @param policyid 策略Id
     * @param currentStateId 当前状态Id
     * @param event 提升/降级
     * @param appointTargetStateId 指定到的状态Id
     * @return 提升/降级 后的状态Id 集合
     */
    private Map<String, Object> getToBeSetStateMap(Long policyid,int currentStateId,String event,Long appointTargetStateId){
//        /*这里的sort 必须在创建状态的时候按照顺序来,即使是后面新增的状态,状态sort值也得修改 同一策略的状态sort 不能一样**/
//        Long selectStateId = parseInt2Long(currentStateId);
//        int currentSort = rdaStateService.selectRdaStateById(selectStateId).getSort();
//        //System.out.println("LifeCycleController:promote--->>>currentSort:" + currentSort);
//        /*获取当前策略下的所有状态**/
//        LifecycleUtil lifecycleUtil = new LifecycleUtil(rdaStateService);
//        return lifecycleUtil.goToAppointTargetState(policyid, event, currentSort,appointTargetStateId);
        return null;
    }






    private Long parseInt2Long(int stateId){
        return Long.parseLong(String.valueOf(stateId));
    }

    private Integer parseString2Int(String stateId){
        return Integer.parseInt(stateId);
    }

    private Integer parseLong2Int(Long stateId){return Integer.parseInt(String.valueOf(stateId));
    }


}
